<template>
  <div class="box">
    <!-- 登录表单 -->
    <div class="loginBox">
      <div class="login-title">登录</div>
      <!-- 登录表单 -->

      <form>
        <div class="title"></div>
        <div class="label">
          <i class="iconfont icon-yonghu2"></i>
          <input
            type="text"
            placeholder="请输入用户名"
            v-model="loginForm.username"
          />
        </div>

        <div class="label">
          <i class="iconfont icon-iconset0114"></i>
          <input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
            ref="repwd"
          />
        </div>
      </form>

      <el-form :model="loginForm" ref="loginFormRef" :rules="loginRules">
        <div class="title"></div>
        <!-- <el-form-item label="" prop="username">
          <i class="iconfont icon-yonghu2"></i>
          <el-input
            v-model="loginForm.username"
            prefix-icon="none"
            placeholder="请输入用户名"
            value=""
          >
          </el-input>
        </el-form-item> -->
        <!-- <el-form-item label="" prop="password">
          <i class="iconfont icon-iconset0114"></i>
          <el-input
            type="password"
            v-model="loginForm.password"
            prefix-icon="none"
            placeholder="请输入密码"
            value=""
            ref="repwd"
          >
          </el-input>
        </el-form-item> -->
        <div class="flexend">
          <router-link class="forgetPwd" to="/forgetpwd"
            >忘记密码？</router-link
          >
        </div>
        <el-form-item label="">
          <el-button type="danger" class="log_class" @click="loginHandle"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="wxBox" label="">
          <div class="scancode">
            <router-link to="/scanLogin"
              ><img src="@/assets/imgs/wx.png" class="wx" alt=""
            /></router-link>
          </div>
        </el-form-item>
        <el-form-item label="">
          <div class="toReg">
            <span>还没有账号</span
            ><span class="regBox">
              <router-link to="/toReg">立即注册</router-link></span
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { post } from "@/utils/http";
import api from "@/config/api";
import userUtil from "@/utils/userUtil";
import { sendPost } from "@/utils/http";

export default {
  name: 'loginreg',
  components: {
  },
  created () {
    var code = this.$route.query.code;
    if (code != null) {
      this.getAccessToken(code);
    }

  },
  mounted () {
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
  },

  data () {
    var checkEmail = (rule, value, callback) => {
      // const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      const mailReg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      loginDialogVisible: true, // 登录框默认展示
      scanloginDialogVisible: false,
      regDialogVisible: false,
      activeIndex: '4',
      // 登录表单对象
      loginForm: {
        username: '',
        password: ''
      },
      // 登录表单校验规则
      loginRules: {
        username: [
          { required: true, message: '邮箱格式不正确', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码输入不合理', trigger: 'blur' }
        ]
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例,将值传入fromPath
      vm.fromPath = from.path
      vm.toPath = to.path
    })
  },
  methods: {
    // 回车登录方法
    keyDown (e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        this.loginHandle();
      }
    },


    // 获取消息数量
    getMessageNum () {
      sendPost(api.getMessageNum, {}).then(res => {
        console.log(res);
        // this.msgNum = res.data
        sessionStorage.setItem('msgNum', res.data)

      })
    },
    // 登录验证操作
    loginHandle () {
      this.$refs.loginFormRef.validate(async valid => {
        // 预校验登录数据不通过
        if (!valid) return

        let that = this
        post(api.login, {
          email: this.loginForm.username,
          password: this.loginForm.password,
        }).then((res) => {

          this.$nextTick(() => {
            // 验证是否获取到了上页的url
            /* eslint-disable no-console */
            console.log(this.fromPath)
            if (res.data.success == '0') {
              userUtil.set(res.data.data)
              this.$nextTick(() => {
                this.getMessageNum()
              })

              if (sessionStorage.getItem('setCom')) {
                if (this.fromPath == '/' || this.fromPath === 'undefined' || this.fromPath === '/toReg' || this.fromPath === '/toLogin'
                  || this.fromPath === '/scanLogin' || this.fromPath === '/forgetpwd') {
                  this.$router.push("/courses")
                } else {

                  this.$router.go(-1)
                }
                // sessionStorage.setItem('activeIndex', 'community')
              } else {

                if (this.fromPath == '/' || this.fromPath === 'undefined' || this.fromPath === '/toReg' || this.fromPath === '/toLogin'
                  || this.fromPath === 'scanLogin' || this.fromPath === '/forgetpwd') {
                  this.$router.push("/courses")
                } else {

                  this.$router.go(-1)
                }

                // sessionStorage.setItem('activeIndex', 'loged')
              }


            } else {
              that.$msg.error(res.data.msg);

            }
          })

          // console.log(res.data)

        })
      })
    },
    beforeRouteEnter (to, from, next) {
      next(vm => {          //  这里的vm指的就是vue实例，可以用来当做this使用
        console.log(to)
        console.log(from)
      })
    },
    // 重置登录表单
    resetLoginForm () {
      this.$refs.loginFormRef.resetFields()
    },

    getAccessToken (code) {
      let that = this
      sendPost(api.getAccToken, { code: code }).then(res => {
        console.log(res);
        var data = res.data;

        if (data.user != null) {
          userUtil.set(data.user)
          that.$router.push("cate")
        } else {
          sessionStorage.setItem("openid", data.openid)
          that.$router.push("toReg")
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-input__inner:focus {
  border-color: #dcdfe6;
}
.el-button {
  width: 22.625rem;
  height: 3.125rem;
}
.iconfont {
  position: absolute;
  left: 0.625rem;
  top: 0.5rem;
  z-index: 1000;
  color: #cfcfcf;
}
.label {
  position: relative;
  margin-bottom: 2.5rem;
  input {
    
    outline: none;
    border: none;
    height: 2.5rem;
    line-height: 2.5rem;
    width: 22.625rem;
    border: 1px solid #dcdfe6;
    padding: 0 30px;
    font-size: 0.875rem;
    &::placeholder{
     color: #cbc7cc;
    }
  }
}
.el-form-item {
  position: relative;
}
header {
  position: absolute;
  top: 0;
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 3.5rem;
  font-size: 1.125rem;
  z-index: 200;
  .logo {
    flex: 0.7;
    text-align: center;
    line-height: 3.75rem;
  }
  .item {
    font-weight: bold;
    text-decoration: none;
    color: #666;
    padding: 0 1.25rem;
    display: inline-block;
    cursor: pointer;
    box-sizing: border-box;
  }
  a {
    text-decoration: none;
    box-sizing: border-box;
  }
}
// 下边框颜色设置为白色
.el-menu.el-menu--horizontal {
  border-bottom: solid 1px #fff;
}
.el-menu {
  background-color: transparent;
  color: #333333;
}
.el-menu-item.is-active {
  background-color: transparent !important;
}
.el-menu-item {
  background-color: rgba(0, 0, 0, 0) !important;
}
.el-menu.el-menu--horizontal {
  border-bottom: none;
}
.icon-lingdang1 {
  color: #eee;
  line-height: 3.75rem;
}
.avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: inline-block;
  vertical-align: middle;
}
.username {
  display: inline-block;
  margin-left: 0.625rem;
  font-weight: bold;
  font-size: 1rem;
  color: #333333;
  width: 6.25rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.loginBox {
  width: 34.5rem;
  height: 34.5rem;
  padding: 0 5.9375rem;
  box-sizing: border-box;
  background-color: #fff;
  margin: auto;
  position: absolute;
  top: 6.25rem;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0px 0px 0.625rem 0px rgba(0, 0, 0, 0.5);
  border-radius: 0.3125rem;
  .login-title {
    font-size: 2rem;
    color: #999999;
    text-align: center;
    height: 8.0625rem;
    line-height: 8.0625rem;
  }
  .forgetPwd {
    font-size: 1rem;
    color: #999999;
    text-decoration: underline;
  }
  .flexend {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 1.875rem;
  }
  .scancode {
    img {
      margin-left: 43%;
    }
  }
  .toReg {
    text-align: center;
    font-size: 1rem;
    .regBox {
      a {
        color: #ff5e4e;
        text-decoration: underline;
      }
    }
  }
}
.log_class {
  font-size: 1.125rem;
}
</style>
